package com.eco.fanliapp.job.hdkitemjob;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.*;


@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class CancelGoodsLabelTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(CancelGoodsLabelTask.class);

    @Autowired
    private IJobOrderInfoGetService jobOrderInfoGetService;

    @Autowired
    private IAppGoodsService appGoodsService;

    @Autowired
    private ISyLabelGoodsService iSyLabelGoodsService;

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;

    @Autowired
    private AppGoodsMapper appGoodsMapper;

    @Autowired
    private FindItemIdUtils taoBaoUtils;
    @Autowired
    private ISyLabelTypeService iSyLabelTypeService;

    public CancelGoodsLabelTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行标签更新定时任务-CancelGoodsLabelTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        CountLauncher countLauncher = new CountLauncher(10);
        jobOrderInfoGetService.setCountLauncher(countLauncher);
        log.info("开始执行标签更新开始  0 * */1 * * ?");
        long startMillions = System.currentTimeMillis();
        int current = 1;
        while (true) {
            try {
                Page<AppGoods> page = new Page<>(current, 500);
                QueryWrapper<AppGoods> queryWrapper = new QueryWrapper<>();
//                queryWrapper.ne("item_top", 2).ne("item_top", 3).eq("recommend", 1).orderByDesc("update_time");
                queryWrapper.in("item_top", 1);
                queryWrapper.eq("recommend", 1);
                queryWrapper.orderByDesc("update_time");
                IPage<AppGoods> appGoodsIPage = appGoodsService.page(page, queryWrapper);
                if (appGoodsIPage.getRecords().size() == 0) {
                    break;
                }
                QueryWrapper<SyLabelType> labelTypeQueryWrapper = new QueryWrapper();
                labelTypeQueryWrapper.eq("enable", 1);
                labelTypeQueryWrapper.eq("deleted", 0);
                List<SyLabelType> labelList = iSyLabelTypeService.list(labelTypeQueryWrapper);

                Set<String> deleteGoodsLabel = new HashSet<>();
                if (appGoodsIPage != null && appGoodsIPage.getRecords() != null) {
                    for (AppGoods appGoods : appGoodsIPage.getRecords()) {
                        AppGoods goods = null;
                        //大淘客
                        DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(appGoods.getItemid());
                        if (dtkResponse != null && dtkResponse.getCode() == 0 && dtkResponse.getData() != null) {
                            goods = HDKUtils.getAppGoodsFromDTK(dtkResponse.getData());
                        } else {
                            //好单库
                            HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(appGoods.getItemid());
                            if (info != null && info.getCode() == 1 && info.getData() != null) {
                                goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                            }
                        }
                        if (goods != null) {
                            if (StringUtils.isNotNull(goods.getActivityType()) && StringUtils.isNotNull(goods.getEndTime())) {
                                if (!goods.getActivityType().equals(appGoods.getActivityType()) || !goods.getEndTime().equals(appGoods.getEndTime())) {
                                    //修改商品
                                    int i = appGoodsMapper.updateGoodsByItemId(appGoods.getItemid(), appGoods.getRecommend(), goods.getActivityType(), goods.getStartTime(), goods.getEndTime());
                                    if (i > 0) {
                                        log.info("修改商品活动类型成功  itemid:" + appGoods.getItemid());
                                    }
                                }

                                if ("聚划算".equals(goods.getActivityType()) || "淘抢购".equals(goods.getActivityType())) {
                                    if (Long.valueOf((goods.getEndTime() == null || "".equals(goods.getEndTime()) || goods.getEndTime().indexOf("null") > -1) ? "0" : goods.getEndTime()) < System.currentTimeMillis()) {
                                        //删除标签
                                        deleteGoodsLabel.add(goods.getItemid());
                                    } else {
                                        SyLabelGoods syLabelGoods = iSyLabelGoodsService.selectGoodsLabel(goods.getItemid(), goods.getActivityType());
                                        if (syLabelGoods == null) {
                                            for (SyLabelType syLabelType : labelList) {
                                                if (syLabelType.getLabelName().equals(goods.getActivityType())) {
                                                    SyLabelGoods labelGoods = new SyLabelGoods();
                                                    labelGoods.setLabelTypeId(syLabelType.getTableId().toString());
                                                    labelGoods.setLabelCode(syLabelType.getLabelCode());
                                                    labelGoods.setItemId(goods.getItemid());
                                                    labelGoods.setUpdateTime(new Date());
                                                    labelGoods.setCreateTime(new Date());
                                                    labelGoods.setEnable(1);
                                                    labelGoods.setDeleted(0);
                                                    //添加商品标签
                                                    iSyLabelGoodsService.addSyLabelGoods(labelGoods);
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    deleteGoodsLabel.add(goods.getItemid());
                                }
                            } else {
                                deleteGoodsLabel.add(goods.getItemid());
                            }
                        }
                    }
                }
                if (deleteGoodsLabel != null && deleteGoodsLabel.size() > 0) {
                    for (String itemid : deleteGoodsLabel) {
                        List<SyLabelGoods> syLabelGoods = iSyLabelGoodsService.findGoodsLabel(itemid);
                        if (syLabelGoods.size() > 0 && syLabelGoods.get(0) != null) {
                            //删除商品标签
                            syLabelGoods.get(0).setDeleted(1);
                            iSyLabelGoodsService.addSyLabelGoods(syLabelGoods.get(0));
                        }
                    }
                }
                current = current + 1;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("标签更新错误");
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束标签更新定时任务-CancelGoodsLabelTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}

